import { _decorator, Component, Tween, tween, Vec2, Node, Vec3, UIOpacity } from "cc";

const { ccclass, property } = _decorator;

@ccclass('GuidedClick')
export class GuidedClick extends Component {
    private target: any = null;
    public set Target(target: any) {
        this.target = target;
    }

    private isLoop: boolean = true;

    public init(pos: Vec3, isLoop: boolean, target: any): void {
        this.node.position = pos.clone();
        this.node.getComponent(UIOpacity).opacity = 0;

        this.isLoop = isLoop;

        tween(this.node.getComponent(UIOpacity))
            .to(0.5, { opacity: 255 })
            .call(this.playClickAnim.bind(this))
            .start();

        this.target = target;
    }

    public moveToInit(startPos: Vec3, endPos: Vec3, dt: number = 1): void {
        this.node.position = startPos.clone();
        this.node.getComponent(UIOpacity).opacity = 0;

        tween(this.node.getComponent(UIOpacity))
            .to(0.3, { opacity: 255 })
            .start();

        tween(this.node)
            .to(dt, { position: endPos }, { easing: 'sineInOut' })
            .call(this.playClickAnim.bind(this))
            .start();
    }

    public playClickAnim(isLoop: boolean = true): void {
        Tween.stopAllByTarget(this.node);

        isLoop = isLoop || this.isLoop;

        if (isLoop) {
            tween(this.node)
                .to(0.3, { scale: new Vec3(0.95, 0.95, 1) })
                .call(() => {
                    if (this.target)
                        this.target.PlayGuidedAnimation(true);
                })
                .to(0.3, { scale: new Vec3(1, 1, 1) })
                .call(() => {
                    if (this.target)
                        this.target.PlayGuidedAnimation(false);
                })
                .union().repeatForever().start();
        }
        else {
            tween(this.node)
                .to(0.3, { scale: new Vec3(0.95, 0.95, 1) })
                .to(0.3, { scale: new Vec3(1, 1, 1) }).start();
        }
    }

    public reset(target: any): void {
        Tween.stopAllByTarget(this.node);

        this.node.scale = new Vec3(1, 1, 1);
        this.target.PlayGuidedAnimation(false);

        this.target = target;
    }
}

